import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStore } from "@/store/modules/user";
import { message } from "./message";

export interface IResult {
  code: number;
  data: any;
  msg: string;
}

const getHost = () => {
  return localStorage.getItem("host");
};
const service = axios.create({
  timeout: 10000
});

service.interceptors.request.use(
  (config: any) => {
    const userStore = useUserStore();
    if (config.headers) {
      config.headers["Token"] = `${userStore.getToken}`;
    }
    if (import.meta.env.VITE_APP_BUILD === "app") {
      if (getHost()) {
        localStorage.setItem("OPEN_LIVE_URL", getHost() as string);
        config.baseURL = getHost() as string;
      } else {
        message.warning("接口异常");
        // 抛出错误以中断请求
        return Promise.reject(new Error("接口异常"));
      }
    }
    return config;
  },
  error => {
    console.log("error---------", error);
    return error.response.data;
  }
);
service.interceptors.response.use(
  res => {
    if (res.data.code == 200) {
      return res;
    } else {
      const userStore = useUserStore();
      if (res.data.code == 10103) {
        message.error("登录已失效");
        setTimeout(() => {
          userStore.logout();
        }, 500);
      } else if (res.data.code == 10104) {
        message.warning(res.data?.message);
      } else {
        message.warning(res.data?.message || "服务繁忙");
      }
    }
    return Promise.reject(res.data);
  },
  error => {
    const userStore = useUserStore();
    const data = error.response.data || error.response;
    if (data.code == 10103) {
      message.error("登录已失效");
      setTimeout(() => {
        userStore.logout();
      }, 500);
    } else if (data.code == 10104) {
      message.warning(data.message);
    } else {
      message.warning(data.message || "服务繁忙");
    }
    return Promise.reject(data);
  }
);

export const request = <T = any>(config: AxiosRequestConfig): Promise<AxiosResult<T>> => {
  return new Promise((resolve, reject) => {
    service(config)
      .then((res: AxiosResponse<AxiosResult<T>>) => {
        resolve(res.data);
      })
      .catch(err => {
        console.log(err);
        reject(err);
      });
  });
};

export default service;
